//
//  HMComposeViewController.swift
//  WB25
//
//  Created by HM on 2017/7/8.
//  Copyright © 2017年 itheima. All rights reserved.
//

import UIKit
import AFNetworking
class HMComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        setupNav()
        // 添加控件
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(bottomView)
        // 添加约束
        textView.snp.makeConstraints { (make) in
            make.top.left.bottom.right.equalTo(view)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: HMSCREENW - 20, height: HMSCREENW - 20))
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
        }
        
        bottomView.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(view)
            make.height.equalTo(35)
        }
        
        
        // 02 闭包的实例化
        bottomView.closure = {[weak self](type)->() in
            // 04 闭包回调
            
            switch type {
            case .picture:
                print("图片")
                self?.selectImage()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("笑脸")
                self?.switchKeyboard()
            case .add:
                print("+")
            }
        }
        
        // 监听配图中加号图片点击
        // 02 04
        pictureView.closure = {[weak self] in
            self?.selectImage()
        }
        
        // 监听系统通知监听键盘
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        // 监听表情键盘20个按钮通知
        NotificationCenter.default.addObserver(self, selector: #selector(emoticonButtonClickNoti), name: HMEMOTICONBUTTONCLICKNOTI, object: nil)
        // 监听表情键盘中删除按钮通知
        NotificationCenter.default.addObserver(self, selector: #selector(deleteButtonClickNoti), name: HMDELETEBUTTONCLICKNOTI, object: nil)
    }
    
    //MARK: - 设置导航
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        // 默认不能点击
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        navigationItem.titleView = titleView
    }
    
    //MARK: - 懒加载控件
    private lazy var sendButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(sendClick), for: UIControlEvents.touchUpInside)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: UIControlState.normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: UIControlState.highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: UIControlState.disabled)
        button.setTitle("发送", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.setTitleColor(UIColor.darkGray, for: UIControlState.disabled)
        button.titleLabel?.font = UIFont.systemFont(ofSize: HMNormalFontSize)
        button.frame.size = CGSize(width: 50, height: 35)
        return button
    }()
    // titleView
    private lazy var titleView: UILabel = {
        // 获取名字
        let name = HMOAuthViewModel.share.userAccountModel?.screen_name ?? ""
        // 最终要显示的文字
        let str = "发微博\n\(name)"
        // 范围
        let range = (str as NSString).range(of: name)
        // 通过字符串获取富文本
        let attr = NSMutableAttributedString(string: str)
        // 设置富文本属性
        attr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: HMThemeColor], range: range)
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.attributedText = attr
        lab.textAlignment = .center
        lab.sizeToFit()
        return lab
    }()
    // 自定义textView
    fileprivate lazy var textView: HMComposeTextView = {
        let view = HMComposeTextView()
        view.placeholder = "黑马25期新浪微博"
//        let txt = UITextField()
////        txt.placeholder
//        view.placeholder
        view.delegate = self
        view.font = UIFont.systemFont(ofSize: 16)
        // 上下滚动
        view.alwaysBounceVertical = true
        return view
    }()
    // 底部视图
    fileprivate lazy var bottomView: HMComposeBottomView = HMComposeBottomView()
    
    // 自定义配图
    fileprivate lazy var pictureView: HMComposePictureView = HMComposePictureView()
    
    // 自定义表情键盘
    fileprivate lazy var keyboardView: HMEmoticonKeyboardView = HMEmoticonKeyboardView()
    
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
//MARK: - 底部视图按钮点击事件监听
extension HMComposeViewController{
    fileprivate func selectImage(){
        // 打开相册
        let pickerVc = UIImagePickerController()
        // 设置代理
        pickerVc.delegate = self
        // 是否可以编辑
//        pickerVc.allowsEditing = true
        // 判断是否可以打开相机 或者相册
//        UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType)
        // 判断前后摄像头是否可用
//        UIImagePickerController.isFlashAvailable(for: UIImagePickerControllerCameraDevice.front)
        self.present(pickerVc, animated: true, completion: nil)
    }
    
    // 切换键盘
    func switchKeyboard(){
        self.textView.inputView = (self.textView.inputView == nil ? keyboardView : nil)
        // 赋值
        self.bottomView.isEmoticon = (self.textView.inputView != nil)
        // 刷新inputView
        self.textView.reloadInputViews()
        // 开启第一响应者
        self.textView.becomeFirstResponder()
    }
}
//MARK: - UIImagePickerControllerDelegate
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        print(info)
        // 通过key 获取image
        guard  let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else{
            return
        }
        // 赋值
        pictureView.addImage(image: image.dealImageScale(maxWidth: 400))
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    
}


//MARK: - UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 取消第一响应者
        self.textView.resignFirstResponder()
    }
}

//MARK: - 监听事件
extension HMComposeViewController{
    @objc fileprivate func cancelClick(){
        dismiss(animated: true, completion: nil)
    }
    
    @objc fileprivate func sendClick(){
        print("发送按钮点击")
        /*
            - 例如textView 显示 A图标a 发送出去 服务器接收到的是 A[马到成功]a
         */
        // 记录最终的字符串
        var allText = ""
        // 遍历(info 每个字付 range 每个字符的范围 最后_ 代表是否停止遍历)
        textView.attributedText.enumerateAttributes(in: NSRange(location: 0, length: textView.attributedText.length), options: []) { (info, range, _) in
            // 图片表情
            if let att = info["NSAttachment"] as? HMTextAttachment {
                allText += (att.emoticonModel?.chs ?? "")
            }else{
                // 字符串
                allText += textView.attributedText.attributedSubstring(from: range).string
            }
        }
        
        print(allText)
        // 发布的图片微博还是文字微博
        pictureView.imageList.count > 0 ? upload(status: allText) : update(status: allText)
    }
    
    // 发送图片和文字微博
    func upload(status: String){
        // 地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求参数
        let params = [
            "access_token": HMOAuthViewModel.share.accessToken,
            "status": status]
        
        // 上传一张图片
        let image = pictureView.imageList.first!
        // 把图片转二进制
        let d = UIImagePNGRepresentation(image)!
        
        // 发送请求
        HMNetworkTools.share.post(urlString, parameters: params, constructingBodyWith: { (formdata) in
            /*
                - 01 上传文件的二进制
                - 02 上传文件服务器指定的名称
                - 03 代表上传二进制文件保存到服务器哪里(可以随意填)
                - 04 上传二进制数据的类型 一半传入application/octet-stream 后台会自动识别类型
             */
            // 单张图片
            formdata.appendPart(withFileData: d, name: "pic", fileName: "testtest", mimeType: "application/octet-stream")
            
//            // 如果是多张图片
//            for image in self.pictureView.imageList{
//                // 把图片转二进制
//                let d = UIImagePNGRepresentation(image)!
//                 formdata.appendPart(withFileData: d, name: "pic", fileName: "testtest", mimeType: "application/octet-stream")
//            }
            
            
        }, progress: nil, success: { (_, response) in
            
        }) { (_, error) in
            
        }
    }
    
    // 发布文字微博
    func update(status: String){
        // url地址
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 请求参数
        let params = [
            "access_token": HMOAuthViewModel.share.accessToken,
            "status": status]
        // 简单的post请求
        HMNetworkTools.share.request(type: HMNetworkToolsType.post, urlString: urlString, parameters: params, success: { (response) in
            
        }) { (error) in
            
        }
    }
}
//MARK: - 监听通知方法
extension HMComposeViewController{
    // 监听键盘frame变化
    @objc fileprivate func keyboardWillChangeFrame(noti: Notification){

        // 判断是否为nil
        guard let userInfo = noti.userInfo else {
            return
        }
        // 获取rect NSRect (NSValue) CGRect
        let rect = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        // 获取动画时长
        let durating = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        // 更新底部视图的底部约束
        self.bottomView.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(rect.origin.y - HMSCREENH)
        }
        // 设置动画
        UIView.animate(withDuration: durating) {
            self.view.layoutIfNeeded()
        }
    }
    // 监听20个表情按钮点击
    @objc fileprivate func emoticonButtonClickNoti(noti: Notification){
        // 判断是否为nil 且是否可以转成emoticonModel
        guard let emoticonModel = noti.object as? HMEmoticonModel else {
            return
        }
        
        // 判断是emoji 还是图片表情
        if emoticonModel.isEmoji {
            // emoji表情
            let code = ((emoticonModel.code ?? "") as NSString).emoji() ?? ""
            // 设置给textView
            textView.insertText(code)
        }else{
            // 图片表情
            // 再每次进入当前判断中后 保存当前 textView.attributedText
            let allAttr = NSMutableAttributedString(attributedString: textView.attributedText)
            // 通过路径获取image
            let allPath = emoticonModel.allPath ?? ""
            // 读取bundle文件中的图片
            let image = UIImage(named: allPath, in: HMEmoticonTools.share.emoticonBundle, compatibleWith: nil)
            // 创建一个文本附件
            let att = HMTextAttachment()
            // 赋值
            att.emoticonModel = emoticonModel
            // 计算行高
            let lineHeight = UIFont.systemFont(ofSize: 16).lineHeight
            // 设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            // 设置image
            att.image = image
            // 创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)

////            // 添加到原富文本中
//            allAttr.append(attr)
            // 获取光标位置
            let selectRange = textView.selectedRange
            // 把点击的表情插入到textView中
//            allAttr.insert(attr, at: selectRange.location)
            // 替换
            allAttr.replaceCharacters(in: selectRange, with: attr)
            // 设置font(一个大马带着一群小马)
            allAttr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: allAttr.length))
            textView.attributedText = allAttr
            // 叫光标位置 + 1
            textView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            // 开发者发送系统通知(使用系统通知名)
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            // textView自己调用其身上的代理执行协议方法
            textView.delegate?.textViewDidChange!(textView)
        }
        
        // 把对应的表情模型进行保存
        HMEmoticonTools.share.saveRecentEmoticon(emoticonModel: emoticonModel)
        // 刷新
        keyboardView.reloadRecentEmoticons()
        
    }
    
    // 监听删除按钮点击通知
    @objc fileprivate func deleteButtonClickNoti(){
        // 删除textView(文字还是图片)
        textView.deleteBackward()
    }
}
